package org.water.common.jcaptcha;
import java.util.Collection;
import java.util.Locale;


import org.apache.commons.collections.CollectionUtils;
import org.water.common.content.SpringContentUtil;

import com.octo.captcha.Captcha;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.captchastore.CaptchaAndLocale;
import com.octo.captcha.service.captchastore.CaptchaStore;

import net.rubyeye.xmemcached.MemcachedClient;
/**
 * 存储
 * @author qzy
 *
 */
public class MemcacheCaptchaStore implements CaptchaStore {

	private Object getCaptchaById(String id) {
		try {
			return getClient().get(id);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private MemcachedClient getClient() {
		Object obj = SpringContentUtil.getBean(MemcachedClient.class);
		if (obj == null) {
			throw new RuntimeException("Not found memcache instance");
		}
		return (MemcachedClient) obj;
	}

	public boolean hasCaptcha(String id) {
		try {
			if (getCaptchaById(id) != null) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public void storeCaptcha(String id, Captcha captcha) throws CaptchaServiceException {
		try {
			getClient().set(id, 1800, new CaptchaAndLocale(captcha));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void storeCaptcha(String id, Captcha captcha, Locale locale) throws CaptchaServiceException {
		try {
			getClient().set(id, 1800, new CaptchaAndLocale(captcha, locale));
		} catch (Exception e) {
			throw new CaptchaServiceException(e);
		}
	}

	public Captcha getCaptcha(String id) throws CaptchaServiceException {
		try {
			Object captchaAndLocale = getCaptchaById(id);
			return captchaAndLocale == null ? null : ((CaptchaAndLocale) captchaAndLocale).getCaptcha();
		} catch (Exception e) {
			throw new CaptchaServiceException(e);
		}
	}

	public Locale getLocale(String id) throws CaptchaServiceException {
		try {
			Object captchaAndLocale = getCaptchaById(id);
			return captchaAndLocale == null ? null : ((CaptchaAndLocale) captchaAndLocale).getLocale();
		} catch (Exception e) {
			throw new CaptchaServiceException(e);
		}
	}

	public boolean removeCaptcha(String id) {
		try {
			if (getCaptcha(id) != null) {
				return getClient().delete(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public int getSize() {
		return 0;
	}

	public Collection<?> getKeys() {
		return CollectionUtils.EMPTY_COLLECTION;
	}

	public void empty() {

	}

	public void initAndStart() {
	}

	public void cleanAndShutdown() {

	}

}
